﻿using Blm.RabbitMQ.MessageQueue;
using Blm.RabbitMQ.Models;
using Blm.Utils.Extensions;
using Meta.RabbitMQ.Generic;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using System;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Domain.DtoModel.RabbitMq;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Utility;
using VisionSurface.Service.Wx;

namespace VisionSurface.Web.Services
{
    public class PushWxMessageService : BlmRabbitMQStorageSubscriberBase<PushWxMessageDto>
    {
        private readonly ILogger<PushWxMessageService> logger;
        private readonly WxApiService wxApiService;
        private readonly IMsTaskRepository taskRepository;
        private readonly IMsTaskWxMessageRepository taskWxMessageRepository;

        public PushWxMessageService(IServiceProvider serviceProvider,
            ILogger<PushWxMessageService> logger,
            WxApiService wxApiService,
            IMsTaskRepository taskRepository,
            IMsTaskWxMessageRepository taskWxMessageRepository) : base(serviceProvider)
        {
            this.logger = logger;
            this.wxApiService = wxApiService;
            this.taskRepository = taskRepository;
            this.taskWxMessageRepository = taskWxMessageRepository;
        }

        public override StorageWayEm StorageWay => StorageWayEm.OnlyStorage;

        public override ushort ThreadCount => 1;

        public override ClientOption ClientOption => new ClientOption("visionsurface.wxmessage.ex", "visionsurface.wxmessage.push.rk", ExchangeType.Topic, "visionsurface.wxmessage.push.queue", RabbitMQConnectPoolName.CloudServerHost);

        public override async Task InvokeAsync(PushWxMessageDto model)
        {
            var list = await taskWxMessageRepository.WhereAsync(p => p.TaskId == model.TaskId && p.Status == 0 && !p.IsDeleted);
            if (list.IsEmpty())
                return;

            var taskInfo = await taskRepository.GetBaseInfoAsync(model.TaskId);
            if (taskInfo == null)
            {
                logger.LogInformation($"任务不存在：TaskId = {model.TaskId}");
                return;
            }

            var message = list.OrderByDescending(p => p.LastUpdatedDate).FirstOrDefault();

            var token = await WeChartApiHelper.GetWxAccessToken();

            var data = wxApiService.GetTemplateData(taskInfo, model.Status.ToString());

            await wxApiService.SendSubscribeMessageAsync(token, message.OpenId, message.TemplateId, data);

            await taskWxMessageRepository.UpdateRangeMessageAsync(list);
        }
    }
}
